package com.fary.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.fary.common.ApiResponse;
import com.fary.dto.PayMerchantInfoDTO;
import com.fary.entity.PayMerchantInfo;
import com.fary.service.PayMerchantInfoService;
import com.fary.service.PayMessageTemplateService;
import com.fary.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/merchant")
@CrossOrigin
public class PayMerchantInfoApi {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PayMerchantInfoService payMerchantInfoService;
    @Autowired
    private PayMessageTemplateService payMessageTemplateService;

    /**
     * 商家入驻接口
     */
    @PostMapping("merchantSettlement")
    public ApiResponse<String> merchantSettlement(@RequestBody PayMerchantInfoDTO payMerchantInfoDTO) {
        // 根据socialCreditCode查询数据库中该数据是否存在
        String socialCreditCode = payMerchantInfoDTO.getSocialCreditCode();
        if (StrUtil.isEmpty(socialCreditCode)) {
            return ApiResponse.error("socialCreditCode is null");
        }
        PayMerchantInfo payMerchantInfoDb = payMerchantInfoService.getBySocialCreditCodePayMerchantInfo(socialCreditCode);
        if (payMerchantInfoDb != null) {
            // 已经提交了该数据无需重复提交数据
            return ApiResponse.error("请勿重复提交..");
        }
        // dto与do转换
        PayMerchantInfo payMerchantInfo = BeanUtil.copyProperties(payMerchantInfoDTO, PayMerchantInfo.class);
        // 根据token获取对应的openid
        String qrCodeToken = payMerchantInfoDTO.getQrCodeToken();
        if (StrUtil.isNotBlank(qrCodeToken)) {
            payMerchantInfo.setContactWxOpenid(redisCache.getCacheObject(qrCodeToken));
        }
        boolean addPayMerchantInfoResult = payMerchantInfoService.addPayMerchantInfo(payMerchantInfo);
        if (addPayMerchantInfoResult) {
            // 商家提交资料---发送消息模板推送
            payMessageTemplateService.notifyMerchantSettlementThread(payMerchantInfo);
        }
        return addPayMerchantInfoResult ? ApiResponse.success("提交成功") : ApiResponse.error("提交失败");
    }
}
